package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.biz.enums.EarMarkType;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.model.EarMarkLife;
import com.dongjiantong.biz.service.EarMarkLifeWriteService;
import com.dongjiantong.biz.service.EarMarksWriteService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.JsonMapper;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.dto.FarmRecordsImmunizationDto;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsImmunizationMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsImmunizationSubMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsImmunization;
import com.dongjiantong.farmrecords.model.FarmRecordsImmunizationSub;
import com.dongjiantong.farmrecords.service.FarmRecordsImmunizationService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * 防疫中心-免疫记录表
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsImmunizationServiceImpl extends ServiceMybatis<FarmRecordsImmunization> implements FarmRecordsImmunizationService {
    private static final ObjectMapper objectMapper = JsonMapper.nonEmptyMapper().getMapper();

    @Resource
    private FarmRecordsImmunizationMapper farmRecordsImmunizationMapper;
    @Resource
    private FarmRecordsImmunizationSubMapper farmRecordsImmunizationSubMapper;

    @Reference(version = "1.0.0")
    public EarMarksWriteService earMarksWriteService;
    @Reference(version = "1.0.0")
    public EarMarkLifeWriteService earMarkLifeWriteService;

    @Override
    public PageInfo<FarmRecordsImmunization> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }

        try {
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsImmunization> list = farmRecordsImmunizationMapper.selectByMap(map);
            return new PageInfo<FarmRecordsImmunization>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * app政府端查询
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    @Override
    public PageInfo<FarmRecordsImmunization> selectByMapApp(Integer pageNum, Integer pageSize, Map map) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }

        try {
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsImmunization> list = farmRecordsImmunizationMapper.selectByMapApp(map);

            List<Long> ids = Lists.newArrayList();
            for (FarmRecordsImmunization farmRecordsImmunization : list) {
                Example example = new Example(FarmRecordsImmunizationSub.class);
                example.createCriteria().andEqualTo("vaccine_id",farmRecordsImmunization.getId());
                List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationSubMapper.selectByExample(example);

                farmRecordsImmunization.setVaccines(farmRecordsImmunizationSubList);
            }

            return new PageInfo<FarmRecordsImmunization>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 按条件查询(牛)
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    @Override
    public PageInfo<FarmRecordsImmunization> selectBullByMap(Integer pageNum, Integer pageSize, Map map) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }

        try {
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsImmunization> list = farmRecordsImmunizationMapper.selectByMap(map);
            return new PageInfo<FarmRecordsImmunization>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 新建一条免疫记录 (免疫记录)
     * @param loginInfo
     * @param farmRecordsImmunizationDto
     * @param toStatus
     * @return
     */
    @Override
    public Map<String, Object> createOne(LoginInfo loginInfo, FarmRecordsImmunizationDto farmRecordsImmunizationDto, Integer toStatus) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }
        if (farmRecordsImmunizationSubMapper == null){
            throw new OPServerException("farmRecordsImmunizationSubMapper 为null,请检查");
        }

        FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationDto.getImmunizationRecord();
        List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationDto.getVaccines();

        Integer fromStatus = farmRecordsImmunization.getStatus();

        //todo 生成单据号
        //单据生成规则暂未定(此处为测试)
        String prefix = "FMY";
        prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
        String number = ReportNumberMakerUtil.create(prefix,farmRecordsImmunizationMapper.findMaxNumber(prefix));
        farmRecordsImmunization.setNumber(number);

        farmRecordsImmunization.setProvince_id(loginInfo.getProvinceId());
        farmRecordsImmunization.setCity_id(loginInfo.getCityId());
        farmRecordsImmunization.setRegion_id(loginInfo.getRegionId());
        farmRecordsImmunization.setStreet_id(loginInfo.getStreetId());
        farmRecordsImmunization.setVillage_id(loginInfo.getVillageId());

        farmRecordsImmunization.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

        //首免的子表信息
        if (farmRecordsImmunizationSubList.get(0) == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"对象为空");
        }
        FarmRecordsImmunizationSub farmRecordsImmunizationSub = farmRecordsImmunizationSubList.get(0);

        if (fromStatus == 0 && toStatus == null) {
            //直接暂存

            //todo 新建免疫记录主体表信息
            farmRecordsImmunizationMapper.createOne(farmRecordsImmunization);


            //todo 免疫记录首免信息 (既 免疫记录子表信息)
            if (farmRecordsImmunization.getId() != null && farmRecordsImmunization.getId() != 0) {
                farmRecordsImmunizationSub.setVaccine_id(farmRecordsImmunization.getId());
                farmRecordsImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsImmunizationSubMapper.createOne(farmRecordsImmunizationSub);
            }

        }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
            //直接提交

            //todo 新建免疫记录主体表信息
            farmRecordsImmunization.setStatus(toStatus);
            farmRecordsImmunizationMapper.createOne(farmRecordsImmunization);

            //todo 免疫记录首免信息 (既 免疫记录子表信息)
            if (farmRecordsImmunization.getId() != null && farmRecordsImmunization.getId() != 0) {
                farmRecordsImmunizationSub.setVaccine_id(farmRecordsImmunization.getId());
                farmRecordsImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsImmunizationSubMapper.createOne(farmRecordsImmunizationSub);
            }

            //todo 备份首免操作的耳标
            if (!Strings.isNullOrEmpty(farmRecordsImmunization.getEar_number_json())) {
                //更新耳标的状态
                List<String> earNumberList = farmRecordsImmunization.getEar_number_list();

                Map<String,Object> earParam = Maps.newHashMap();
                earParam.put("markNumbers",earNumberList);
                earParam.put("status", EarMarkType.status_wear.getCode());
                earParam.put("woreAt",new Date());

                earMarksWriteService.updateMarks(earParam);

                //新增耳标的使用记录
                List<EarMarkLife> earMarkLiveList = Lists.newArrayList();
                for (String earNumber : earNumberList) {
                    if (!Strings.isNullOrEmpty(earNumber)) {
                        EarMarkLife earMarkLife = new EarMarkLife();
                        earMarkLife.setMark_number(earNumber);
                        earMarkLife.setMark_type(farmRecordsImmunization.getBreed_second_type());
                        earMarkLife.setReport_id(farmRecordsImmunization.getId());
                        earMarkLife.setReport_name(farmRecordsImmunization.getNumber());
                        earMarkLife.setReport_type(ReportType.IMMUNIZATION_RECORD_MANAGER.value());
                        earMarkLife.setIs_selected(1);
                        earMarkLife.setOperator_id(loginInfo.getId());
                        earMarkLife.setOperator_name(loginInfo.getRealName());
                        earMarkLife.setCreated_at(new Date());
                        earMarkLiveList.add(earMarkLife);
                    }
                }

                earMarkLifeWriteService.insertList(earMarkLiveList);
            }
        }

        //todo 生成日志记录

        Map<String,Object> result = Maps.newHashMap();
        if (farmRecordsImmunization.getId() != null && farmRecordsImmunization.getId() != 0) {
            result.put("receiptId", farmRecordsImmunization.getId());
        }
        if (farmRecordsImmunizationSub.getId() != null && farmRecordsImmunizationSub.getId() != 0) {
            result.put("subId", farmRecordsImmunizationSub.getId());
        }

        return result;
    }

    @Override
    public Map<String,Object> createCowOne(LoginInfo loginInfo,FarmRecordsImmunizationDto farmRecordsImmunizationDto,Integer toStatus) {
        FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationDto.getImmunizationRecord();
        List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationDto.getVaccines();

        Integer fromStatus = farmRecordsImmunization.getStatus();

        //todo 生成单据号
        //单据生成规则暂未定(此处为测试)
        String prefix = "FMY";
        prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
        String number = ReportNumberMakerUtil.create(prefix,farmRecordsImmunizationMapper.findMaxNumber(prefix));
        farmRecordsImmunization.setNumber(number);

        farmRecordsImmunization.setProvince_id(loginInfo.getProvinceId());
        farmRecordsImmunization.setCity_id(loginInfo.getCityId());
        farmRecordsImmunization.setRegion_id(loginInfo.getRegionId());
        farmRecordsImmunization.setStreet_id(loginInfo.getStreetId());
        farmRecordsImmunization.setVillage_id(loginInfo.getVillageId());

        farmRecordsImmunization.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

        //首免的子表信息
        if (farmRecordsImmunizationSubList.get(0) == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"对象为空");
        }
        FarmRecordsImmunizationSub farmRecordsImmunizationSub = farmRecordsImmunizationSubList.get(0);

        if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
            //直接提交

            //todo 新建免疫记录主体表信息
            farmRecordsImmunization.setStatus(toStatus);
            farmRecordsImmunizationMapper.createOne(farmRecordsImmunization);

            //todo 免疫记录首免信息 (既 免疫记录子表信息)
            if (farmRecordsImmunization.getId() != null && farmRecordsImmunization.getId() != 0) {
                farmRecordsImmunizationSub.setVaccine_id(farmRecordsImmunization.getId());
                farmRecordsImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsImmunizationSubMapper.createOne(farmRecordsImmunizationSub);
            }
        }

        Map<String,Object> result = Maps.newHashMap();
        if (farmRecordsImmunization.getId() != null && farmRecordsImmunization.getId() != 0) {
            result.put("receiptId", farmRecordsImmunization.getId());
        }
        if (farmRecordsImmunizationSub.getId() != null && farmRecordsImmunizationSub.getId() != 0) {
            result.put("subId", farmRecordsImmunizationSub.getId());
        }

        return result;
    }

    /**
     * 牛档案更新免疫记录
     */
    @Override
    public Map<String,Object> updateCowByIdOrNumber(LoginInfo loginInfo,FarmRecordsImmunizationDto farmRecordsImmunizationDto,Integer toStatus) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }

        Map<String,Object> result = Maps.newHashMap();

        try {
            FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationDto.getImmunizationRecord();
            List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationDto.getVaccines();
            List<String> original_ear_list = farmRecordsImmunizationDto.getOriginal_ear();

            if (toStatus != null) {
                farmRecordsImmunization.setStatus(toStatus);
            }
            farmRecordsImmunization.setUpdated_at(new Date());
            //todo 更新主表中的数据
            farmRecordsImmunizationMapper.updateByPrimaryKeySelective(farmRecordsImmunization);

            if (farmRecordsImmunizationSubList.size() == 1) {
                for (FarmRecordsImmunizationSub farmRecordsImmunizationSub : farmRecordsImmunizationSubList) {
                    //todo 更新子表数据
                    int con = farmRecordsImmunizationSubMapper.updateByPrimaryKeySelective(farmRecordsImmunizationSub);

                    if (con != 0) {
                        result.put("update",true);
                    }else {
                        result.put("update",false);
                    }
                }
            } else if (farmRecordsImmunizationSubList.size() > 1) {
                //新增免疫子表信息
                FarmRecordsImmunizationSub farmRecordsImmunizationSub = farmRecordsImmunizationSubList.get(farmRecordsImmunizationSubList.size() - 1);
                farmRecordsImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsImmunizationSubMapper.createOne(farmRecordsImmunizationSub);

                if (farmRecordsImmunizationSub.getId() != null) {
                    result.put("receiptId",farmRecordsImmunizationSub.getId());
                }
            }

            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }


    /**
     * 根据子表id更新免疫主表和免疫子表中的信息
     * @param farmRecordsImmunizationDto
     * @param toStatus
     * @return
     */
    @Override
    public Integer updateByIdOrNumber(LoginInfo loginInfo,FarmRecordsImmunizationDto farmRecordsImmunizationDto,Integer toStatus) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }

        try {
            FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationDto.getImmunizationRecord();
            List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationDto.getVaccines();
            List<String> original_ear_list = farmRecordsImmunizationDto.getOriginal_ear();

            if (toStatus != null) {
                farmRecordsImmunization.setStatus(toStatus);
            }
            farmRecordsImmunization.setUpdated_at(new Date());
            //todo 更新主表中的数据
            Integer con = farmRecordsImmunizationMapper.updateByPrimaryKeySelective(farmRecordsImmunization);

            if (farmRecordsImmunizationSubList.size() == 1) {
                for (FarmRecordsImmunizationSub farmRecordsImmunizationSub : farmRecordsImmunizationSubList) {
                    //todo 更新子表数据
                    farmRecordsImmunizationSubMapper.updateByPrimaryKeySelective(farmRecordsImmunizationSub);
                }
            } else if (farmRecordsImmunizationSubList.size() > 1) {
                //新增免疫子表信息
                FarmRecordsImmunizationSub farmRecordsImmunizationSub = farmRecordsImmunizationSubList.get(farmRecordsImmunizationSubList.size() - 1);
                farmRecordsImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsImmunizationSubMapper.createOne(farmRecordsImmunizationSub);
            }

            //更新耳标数据
            this.updateEarNumber(loginInfo,farmRecordsImmunization,original_ear_list);

            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    /**
     * 根据免疫主表id 查询免疫记录
     * @param id
     * @return
     */
    @Override
    public FarmRecordsImmunizationDto selectById(Long id) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }

        try {
            FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationMapper.selectById(id);
            FarmRecordsImmunizationDto farmRecordsImmunizationDto = null;
            if (farmRecordsImmunization != null) {
                farmRecordsImmunizationDto =  new FarmRecordsImmunizationDto();
                List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationSubMapper.selectByVaccineId(farmRecordsImmunization.getId());

                farmRecordsImmunizationDto.setImmunizationRecord(farmRecordsImmunization);
                farmRecordsImmunizationDto.setVaccines(farmRecordsImmunizationSubList);

                if (!Strings.isNullOrEmpty(farmRecordsImmunization.getEar_number_json())) {
                    farmRecordsImmunizationDto.setOriginal_ear(farmRecordsImmunization.getEar_number_list());
                }
            }
            return farmRecordsImmunizationDto;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public FarmRecordsImmunization selectByIdWeb(Long id) {
        if (farmRecordsImmunizationMapper == null){
            throw new OPServerException("farmRecordsImmunizationMapper 为null,请检查");
        }

        try {
            FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationMapper.selectById(id);
            List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationSubMapper.selectByVaccineId(farmRecordsImmunization.getId());
            farmRecordsImmunization.setVaccines(farmRecordsImmunizationSubList);

            return farmRecordsImmunization;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 根据牛档案关联id 查询免疫记录
     * @param cowRecordId
     * @return
     */
    @Override
    public FarmRecordsImmunization selectBullImmunization(Long cowRecordId) {
        Map<String,Object> map = Maps.newHashMap();
        map.put("cow_record_id",cowRecordId);
        //免疫主表信息
        FarmRecordsImmunization farmRecordsImmunization = farmRecordsImmunizationMapper.selectOneByMap(map);

        if (farmRecordsImmunization != null && farmRecordsImmunization.getId() != null) {
            List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationSubMapper.selectByVaccineId(farmRecordsImmunization.getId());
            if (farmRecordsImmunizationSubList.size() > 0) { farmRecordsImmunization.setVaccines(farmRecordsImmunizationSubList); }
        }

        return farmRecordsImmunization;
    }

    /**
     * 根据关联牛档案Ids 查询对应的免疫次数
     * @param ids
     * @return
     */
    @Override
    public List<Map<String, Object>> selectImmunizationCount(List<Long> ids){
        Map<String,Object> map = Maps.newHashMap();
        map.put("ids",ids);
        List<Map<String, Object>> result = farmRecordsImmunizationMapper.selectImmunizationCount(map);
        return result;
    }

    @Override
    public PageInfo<FarmRecordsImmunization> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId, Integer nonBull) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null) {
            map.put("status",status);
        }

        map.put("farm_id",farmId);
        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsImmunization> farmRecordsImmunizationList = farmRecordsImmunizationMapper.selectListByStatus(map);

        for (FarmRecordsImmunization farmRecordsImmunization : farmRecordsImmunizationList) {
            Example example = new Example(FarmRecordsImmunizationSub.class);
            example.createCriteria().andEqualTo("vaccine_id",farmRecordsImmunization.getId());
            List<FarmRecordsImmunizationSub> farmRecordsImmunizationSubList = farmRecordsImmunizationSubMapper.selectByExample(example);

            farmRecordsImmunization.setVaccines(farmRecordsImmunizationSubList);
        }

        return new PageInfo<FarmRecordsImmunization>(farmRecordsImmunizationList);
    }

    /**
     * 更新耳标(耳标状态,耳标使用记录)
     * @param farmRecordsImmunization
     * @param original_ear_list
     * @return
     */
    @Override
    public Boolean updateEarNumber(LoginInfo loginInfo,FarmRecordsImmunization farmRecordsImmunization, List<String> original_ear_list) {

        if (farmRecordsImmunization == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,HttpCode.BAD_REQUEST.getMessage());
        }

        List<String> earNumberList = farmRecordsImmunization.getEar_number_list();
        boolean result = false;
        boolean after = false;
        boolean before = false;

        if (earNumberList != null) {
            //比对两组耳标
            if (earNumberList.size() > 0) {
                if (original_ear_list.size() > 0) {
                    Collection collection = Lists.newArrayList(earNumberList);
                    collection.retainAll(original_ear_list);

                    //取出earNumberList 里新增的耳标
                    earNumberList.removeAll(collection);

                    //取出original_ear_list 里需要 更改成 未使用状态的耳标
                    original_ear_list.removeAll(collection);
                }
            }

            //对新增耳标操作
            if (earNumberList.size() > 0) {
                //修改耳标为配标状态
                //更新耳标的状态
                Map<String,Object> earParam = Maps.newHashMap();
                earParam.put("markNumbers",earNumberList);
                earParam.put("status", EarMarkType.status_wear.getCode());
                earParam.put("woreAt",new Date());

                after = earMarksWriteService.updateMarks(earParam);

                //新增耳标的使用记录
                List<EarMarkLife> earMarkLiveList = Lists.newArrayList();
                for (String earNumber : earNumberList) {
                    EarMarkLife earMarkLife = new EarMarkLife();
                    earMarkLife.setMark_number(earNumber);
                    earMarkLife.setMark_type(farmRecordsImmunization.getBreed_second_type());
                    earMarkLife.setReport_id(farmRecordsImmunization.getId());
                    earMarkLife.setReport_name(farmRecordsImmunization.getNumber());
                    earMarkLife.setReport_type(ReportType.IMMUNIZATION_RECORD_MANAGER.value());
                    earMarkLife.setIs_selected(1);
                    earMarkLife.setOperator_id(loginInfo.getId());
                    earMarkLife.setOperator_name(loginInfo.getRealName());
                    earMarkLife.setCreated_at(new Date());
                    earMarkLiveList.add(earMarkLife);
                }

                earMarkLifeWriteService.insertList(earMarkLiveList);

            }

            //对原有需要更新为未使用状态的耳标操作
            if (original_ear_list.size() > 0) {
                //更新耳标使用状态为入库状态
                //更新耳标的状态
                Map<String,Object> earParam = Maps.newHashMap();
                earParam.put("markNumbers",original_ear_list);
                earParam.put("status", EarMarkType.status_put.getCode());
                earParam.put("createdAt",new Date());

                before = earMarksWriteService.updateMarks(earParam);

            }
        }

        if (after && before) {
            result = true;
        }
        return result;
    }

    /**
    * 根据养殖场ID和时间区间查询免疫次数
    * */
    @Override
    public Integer selectCountByFarmId(Long farmId, Date startDate, Date endDate) {
        Map<String,Object> map = Maps.newHashMap();
        if (farmId != null) {
            map.put("farmId",farmId);
        }
        if (startDate != null) {
            map.put("startDate",startDate);
        }
        if (endDate != null) {
            map.put("endDate",endDate);
        }
        Integer count = farmRecordsImmunizationMapper.selectCountByFarmId(map);
        return count;
    }

    @Override
    public Integer updateEarNumberByCowRelateId(Long cowRelateId,String ear_tag_number) {
        Integer con = 0;
        if (!Strings.isNullOrEmpty(ear_tag_number) && cowRelateId != null) {
            String earNumber = "[]";
            try {
                earNumber = (String) objectMapper.writeValueAsString(Lists.newArrayList(ear_tag_number));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            Map<String,Object> map = Maps.newHashMap();
            map.put("ear_number_json",earNumber);
            map.put("cow_relate_id",cowRelateId);
            con = farmRecordsImmunizationMapper.updateEarNumberByCowRelateId(map);
        }
        return con;
    }
}
